import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wan_android/pages/home_page/home_page.dart';

/// 实现功能如下：
/// 1. 动态获取 web 页面标题
/// 2. 清空缓存，重新刷新加载当前页面
/// 3. 调起默认浏览器打开当前页面
/// 4. 控制 webview 内 web 页面前进后退
/// 5. 关闭当前 webview 同时开启新的 webview

class WebviewPage extends StatefulWidget {

  final String url;
  const WebviewPage({super.key, required this.url});

  @override
  State<WebviewPage> createState() => _WebviewPageState();
}

class _WebviewPageState extends State<WebviewPage> {
  InAppWebViewController? webViewController;
  String _title = '';

  void sendDeviceInfoToWebPage() {
    // 假设获取设备信息的方法
    String deviceInfo = "{\"platform\": \"IOS\", \"version\": \"1.0\"}";
    // 调用JavaScript bridge方法发送数据
    webViewController?.evaluateJavascript(
        source: "receiveDeviceInfoFromApp('$deviceInfo');");
  }
  
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.blueAccent,
          title: Text(_title),
          centerTitle: true,
          actions: [
            // 使用默认浏览器打开当前页面
            IconButton(
              icon: const Icon(Icons.open_in_browser, color: Colors.white,),
              onPressed: () async {
                // Uri url = Uri.parse(widget.url);
                WebUri url = WebUri(widget.url);
                if (await canLaunchUrl(url)) {
                  await launchUrl(url);
                } else {
                  throw '无法运行 $url';
                }
              },
            ),

            // 清空缓存，刷新重新加载页面
            IconButton(
              icon: const Icon(Icons.refresh, color: Colors.white,),
              onPressed: () async {
                if (webViewController != null) {
                  await InAppWebViewController.clearAllCache();
                  webViewController!.reload();
                }
              },
            )
          ],
        ),

        // 页面前进后退
        bottomNavigationBar: BottomAppBar(
          // height: 84.h,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              IconButton(
                disabledColor: Colors.grey,
                // enableFeedback: webViewController?.canGoBack() ?? false,
                icon: const Icon(Icons.arrow_back),
                onPressed: () async {
                  if (await webViewController?.canGoBack() ?? false) {
                    webViewController?.goBack();
                  }
                },
              ),
              IconButton(
                icon: const Icon(Icons.arrow_forward),
                disabledColor: Colors.red,
                // enableFeedback: webViewController?.canGoForward() ?? false,
                onPressed: () async {
                  if (await webViewController?.canGoForward() ?? false) {
                    webViewController?.goForward();
                  }
                },
              )
            ],
          ),
        ),
        body: InAppWebView(
          initialSettings: InAppWebViewSettings(
            javaScriptEnabled: true,
            allowFileAccessFromFileURLs: true,
            allowUniversalAccessFromFileURLs: true
          ),
          initialUrlRequest: URLRequest(url: WebUri(widget.url)),
          // initialUrlRequest: URLRequest(url: WebUri('https://fun.com:3000/')),
          onWebViewCreated: (InAppWebViewController controller) {
            webViewController = controller;
          },
          onLoadStart: (controller, url) {
            print("Started loading: $url");
            print('++++++++++++++++++++++');
            // 监听 URL 变化
            if (url.toString().contains("some_condition")) {
              // 关闭当前 WebView 并打开新的 WebView
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) => NewWebViewPage(url: url.toString()),
                ),
              );
            }
          },
          onLoadStop: (controller, url) async {
            print("Stopped loading: $url");

            String title = (await controller.getTitle())?? '';
            print('================================ $title');
            print(_title);
            setState(() {
              _title = title;
            });
            // 发送设备信息到H5页面
            // sendDeviceInfoToWebPage();
          },
          onProgressChanged: (controller, progress) async {
            print("进度: $progress");
            if (progress == 100) {
              String? title = await controller.getTitle();
              print('标题==========');
              print(title);
              setState(() {
                _title = title ?? '无标题';
              });
            }
          },
          onReceivedError: (controller, request, error ) {
            print('error');
          }
        ),
      ),
    );
  }
}


class NewWebViewPage extends StatelessWidget {
  final String url;

  const NewWebViewPage({super.key, required this.url});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('New WebView Page'),
      ),
      body: InAppWebView(
        initialUrlRequest: URLRequest(url: WebUri(url)),
      ),
    );
  }
}